#!/usr/local/bin/python3.6
# encoding=utf8
import io, sys
import time, base64, urllib.parse
from apps.Aira2Api import Aria2Api
from apps.TaskApi import TaskApi
from modules.Aria2JsonRpc import Aria2JsonRpcError
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


task_api = TaskApi()
aira2_rpc = Aria2Api()


def main():

    try:
        remote_tasks = task_api.get_tasks()

        if remote_tasks['status'] and remote_tasks['data']:
            tasks_data = remote_tasks['data']

            for task in tasks_data:
                #print(task)
                report_data = {}

                operation = str(task['operation']).strip().lower()
                if operation == 'start':
                    write_log("starting task:{}".format(task))
                    start_task_report_data = start_task(task)
                    report_data.update(start_task_report_data)

                elif operation == 'pause':
                    download_id = str(task['download_id']).strip()
                    try:
                        aira2_rpc.pause(download_id)
                    except Aria2JsonRpcError as e:
                        rpc_error = "pause task failed: {} ,connection_error:{}".format(e, e.connection_error)
                        write_log(rpc_error)
                        report_data['download_status'] = "can't pause"
                        report_data['error'] = rpc_error
                    else:
                        write_log("pause task success,download_id:{}".format(download_id))
                        report_data['clear_operation'] = operation
                        report_data['download_status'] = "paused"
                        report_data['error'] = ""

                elif operation == 'remove':
                    download_id = str(task['download_id']).strip()
                    try:
                        aira2_rpc.remove(download_id)
                        aira2_rpc.removeDownloadResult(download_id)
                    except Aria2JsonRpcError as e:
                        rpc_error = "remove task failed: {} ,connection_error:{}".format(e, e.connection_error)
                        write_log(rpc_error)
                        report_data['download_status'] = "can't remove"
                        report_data['error'] = rpc_error
                    else:
                        write_log("remove task success,download_id:{}".format(download_id))
                        report_data['remove_task'] = 'true'

                else:
                    download_id = str(task['download_id']).strip()
                    try:
                        rpc_re = aira2_rpc.tellStatus(download_id)
                    except Aria2JsonRpcError as e:
                        rpc_error = "query task status failed: {} ,connection_error:{}".format(e, e.connection_error)
                        write_log(rpc_error)
                        report_data['download_status'] = "can't query status"
                        report_data['error'] = rpc_error
                    else:
                        write_log("query task status success:{}".format(rpc_re))
                        save_path = rpc_re['dir']
                        if save_path[-1] != '/':
                            save_path += '/'

                        save_name = []
                        if rpc_re['files']:
                            for file in rpc_re['files']:
                                if file['path']:
                                    file_path = file['path']
                                    if file_path.find(save_path) == 0:
                                        file_path = file_path[len(save_path):]

                                    save_name.append(file_path)

                        report_data['save_path'] = save_path
                        report_data['save_name'] = "".join(save_name)
                        report_data['size_total'] = rpc_re['totalLength']
                        report_data['size_download'] = rpc_re['completedLength']
                        report_data['download_speed'] = rpc_re['downloadSpeed']
                        report_data['download_status'] = rpc_re['status']
                        if rpc_re['status'] == 'complete':
                            report_data['task_status'] = 'true'
                        elif rpc_re['status'] == 'error':
                            report_data['task_status'] = 'false'
                            report_data['error'] = rpc_re['errorMessage']

                if report_data:
                    report_data['task_id'] = task['id']
                    write_log("report data:{}".format(report_data))
                    report_re = task_api.report(report_data)
                    write_log("report result:{}".format(report_re))
                else:
                    write_log('no data need report')
                write_log('==========================')
        else:
            write_log('task api return false or no tasks,return data:{}'.format(remote_tasks))

    except:
        write_log('task api error:{}'.format(sys.exc_info()))

    time.sleep(30)
    main()


def start_task(task):

    report_data = {}

    save_name = str(task['save_name']).strip()
    save_path = str(task['save_path']).strip()
    if save_name or save_path:
        options = {}
        if save_name:
            options['out'] = save_name
        if save_path:
            options['dir'] = save_path
    else:
        options = None

    try:
        download_id = str(task['download_id']).strip()
        is_torrent = task['is_torrent']
        download_uri = str(task['uri']).strip()
        torrent_data = str(task['torrent_data']).strip()

        if download_id:
            aira2_rpc.unpause(download_id)
        elif is_torrent and torrent_data:
            download_id = aira2_rpc.addTorrent(torrent_data, options=options)
        elif download_uri:
            download_id = aira2_rpc.addUri([download_uri], options=options)

        if download_id:
            write_log("start task success,download_id:{}".format(download_id))
            report_data['download_id'] = download_id
            report_data['clear_operation'] = 'start'
            report_data['download_status'] = ""
            report_data['error'] = ""

    except Aria2JsonRpcError as e:
        rpc_error = "start task failed: {} ,connection_error:{}".format(e, e.connection_error)
        write_log(rpc_error)

        report_data['download_status'] = "can't started"
        report_data['error'] = "{}".format(rpc_error)

    return report_data


def write_log(msg):
    log_line = "{} : {} \n".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), msg)
    print(log_line)


main()
